<?php

namespace app\admin\controller;

use support\Request;
use app\admin\service\LoginService;
use Webman\Captcha\CaptchaBuilder;

class LoginController extends BaseController
{
    protected array $noNeedLogin = ['index', 'checkLogin', 'captcha', 'logout'];

    public function __construct(LoginService $service)
    {
        parent::__construct();
        $this->service = $service;
    }

    public function index(Request $request)
    {
        return $this->fetch('login/index');
    }

    public function checkLogin(Request $request)
    {
        $input = input();
        $captcha = $request->session()->get('captcha');

        if (empty($input['username']) || empty($input['password'])) {
            return json(['code' => -1, 'msg' => '用户名或密码不能为空']);
        }
        if (empty($input['captcha']) || strtolower($input['captcha']) !== $captcha) {
            return json(['code' => -1, 'msg' => '输入的验证码不正确']);
        }

        $where = [];
        $where[] = ['username', '=', $input['username']];

        return $this->service->loginCheck($request,$where);
    }

    /**
     * 输出验证码图像
     */
    public function captcha(Request $request)
    {
        // 初始化验证码类
        $builder = new CaptchaBuilder;
        // 生成验证码
        $builder->build();
        // 将验证码的值存储到session中
        $request->session()->set('captcha', strtolower($builder->getPhrase()));
        // 获得验证码图片二进制数据
        $img_content = $builder->get();
        // 输出验证码二进制数据
        return response($img_content, 200, ['Content-Type' => 'image/jpeg']);
    }

    /**
     * @param Request $request
     * @return \support\Response
     */
    public function logout(Request $request)
    {
        return $this->service->loginOut($request);
    }

    /**
     * @param Request $request
     * @return \support\Response
     * @throws \Exception
     */
    public function unlock(Request $request)
    {
        $input = $request->post();
        $pwd = md5($input['password']);
        $act = $input['act'];

        $session = $request->session();
        $has = $session->has('admin_lock');
        if($has && $act == 'unlock'){
            $admin_lock = session('admin_lock');
            if($admin_lock === $pwd){
                return json(['code' => 1, 'msg' => 'success']);
            }else{
                return json(['code' => -1, 'msg' => '解锁密码错误']);
            }
        }else{
            $session->set('admin_lock', $pwd);
            return json(['code' => 1, 'msg' => 'success']);
        }
    }

}